<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>登录</title>
  <style>
    body {
      font-family: sans-serif;
      margin: 50px auto;
      max-width: 300px;
      text-align: center;
    }
    input {
      display: block;
      margin: 10px auto;
      padding: 8px;
      width: 100%;
    }
    button {
      padding: 8px 16px;
    }
    #msg {
      color: red;
      margin-top: 10px;
    }
  </style>
</head>
<body>
<h2>登录</h2>
<form id="loginForm">
  <input type="text" id="username" placeholder="用户名" required />
  <input type="password" id="password" placeholder="密码" required />
  <button type="submit">登录</button>
</form>
<p id="msg"></p>

<script>
  const form = document.getElementById('loginForm');
  const username = document.getElementById('username');
  const password = document.getElementById('password');
  const msg = document.getElementById('msg');
  const button = form.querySelector('button');

  form.onsubmit = async (e) => {
    e.preventDefault();
    msg.textContent = '';
    button.disabled = true;
    button.textContent = '登录中...';

    if (!username.value || !password.value) {
      msg.textContent = '请输入用户名和密码';
      button.disabled = false;
      button.textContent = '登录';
      return;
    }

    try {
      const res = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          username: username.value,
          password: password.value,
        }),
      });

      if (res.ok) {
        const data = await res.json();
        localStorage.setItem('token', data.token); // 保存token
        window.location.href = '/index.html'; // 跳转到个人页
      } else if (res.status === 401) {
        msg.textContent = '用户名或密码错误';
      } else {
        msg.textContent = '登录失败，请稍后重试';
      }
    } catch (err) {
      msg.textContent = '网络错误，请检查连接';
    } finally {
      button.disabled = false;
      button.textContent = '登录';
    }
  };
</script>
</body>
</html>
